package com.secneo.appshare.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.secneo.appshare.R;
import com.secneo.appshare.api.RemoteApi.OtherUserApp;

public class OtherUserAppAdapter extends BaseAdapter {

	private Context ctx;
	private List<OtherUserApp> mList; 
	
	public OtherUserAppAdapter(Context ctx, List<OtherUserApp> list) {
		this.ctx = ctx;
		this.mList = list;
	}
	
	public void freeDrawable()
	{
		for (int i = 0; i < mList.size(); i++)
		{
			if (!mList.get(i).icon_url.contains("buildin") &&
					mList.get(i).icon_drawable != null)
			{
				BitmapDrawable a = (BitmapDrawable) mList.get(i).icon_drawable;
				if (a != null && !a.getBitmap().isRecycled())
					a.getBitmap().recycle();
				mList.get(i).icon_drawable = null;
			}
		}
		//mList.clear();
		System.gc();
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		OtherUserApp otherUserApp;
		otherUserApp = mList.get(position);
		AppItem appItem;
		if (convertView == null) {
			View v = LayoutInflater.from(ctx).inflate(R.layout.appshare_app_item, null);
			
			appItem = new AppItem();
			appItem.mAppIcon = (ImageView)v.findViewById(R.id.ivAppIcon);
			appItem.mAppName = (TextView)v.findViewById(R.id.tvAppName);
			appItem.selfAppIcon = (ImageView)v.findViewById(R.id.weiboAppIcon);
			v.setTag(appItem);
			convertView = v;
		} else {
			appItem = (AppItem)convertView.getTag();
		}
		// set icon
		if (otherUserApp.icon_drawable == null) {
			appItem.mAppIcon.setImageResource(R.drawable.some_app);
		} else {
			appItem.mAppIcon.setImageDrawable(otherUserApp.icon_drawable);
		}
		if(otherUserApp.selfAppFlag)
		{
			appItem.selfAppIcon.setVisibility(View.VISIBLE);
			appItem.selfAppIcon.setImageResource(R.drawable.self_app);	
		}
		else
		{
			appItem.selfAppIcon.setVisibility(View.INVISIBLE);
		}
		// set name
		appItem.mAppName.setText(otherUserApp.name);
		
		return convertView;
	}
	
	class AppItem {
		ImageView mAppIcon;
		TextView mAppName;
		ImageView selfAppIcon;
	}

}
